#include "resource_store.h"

SDL_Texture *ResourceStore::getTexture(const std::string &path)
{
    auto it = texture_map_.find(path);
    if (it != texture_map_.end())
    {
        return it->second;
    }
    else
    {
        loadTexture(path);
        return texture_map_[path];
    }
}
Mix_Chunk *ResourceStore::getSound(const std::string &path)
{
    auto it = sound_map_.find(path);
    if (it != sound_map_.end())
    {
        return it->second;
    }
    else
    {
        loadSound(path);
        return sound_map_[path];
    }
}
TTF_Font *ResourceStore::getFont(const std::string &path, int size)
{
    auto it = font_map_.find(path + std::to_string(size));
    if (it != font_map_.end())
    {
        return it->second;
    }
    else
    {
        loadFont(path, size);
        return font_map_[path + std::to_string(size)];
    }
}
Mix_Music *ResourceStore::getMusic(const std::string &path)
{
    auto it = music_map_.find(path);
    if (it != music_map_.end())
    {
        return it->second;
    }
    else
    {
        loadMusic(path);
        return music_map_[path];
    }
}

void ResourceStore::loadTexture(const std::string &path)
{
    SDL_Texture *texture = IMG_LoadTexture(renderer_, path.c_str());
    if (texture == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to load texture: %s", SDL_GetError());
        return;
    }
    texture_map_.emplace(path, texture);
}
void ResourceStore::loadSound(const std::string &path)
{
    Mix_Chunk *sound = Mix_LoadWAV(path.c_str());
    if (sound == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to load sound: %s", SDL_GetError());
        return;
    }
    sound_map_.emplace(path, sound);
}
void ResourceStore::loadFont(const std::string &path, int size)
{
    TTF_Font *font = TTF_OpenFont(path.c_str(), static_cast<float>(size));
    if (font == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to load font: %s", SDL_GetError());
        return;
    }
    font_map_.emplace(path + std::to_string(size), font);
}
void ResourceStore::loadMusic(const std::string &path)
{
    Mix_Music *music = Mix_LoadMUS(path.c_str());
    if (music == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to load music: %s", SDL_GetError());
        return;
    }
    music_map_.emplace(path, music);
}
void ResourceStore::clear()
{
    for (auto &pair : texture_map_)
    {
        SDL_DestroyTexture(pair.second);
    }
    for (auto &pair : sound_map_)
    {
        Mix_FreeChunk(pair.second);
    }
    for (auto &pair : font_map_)
    {
        TTF_CloseFont(pair.second);
    }
    for (auto &pair : music_map_)
    {
        Mix_FreeMusic(pair.second);
    }
}